import { supabase } from "./supabase";
import { getUser } from "./auth";

export interface LeadData {
  lead_id: string;
  user_id: string;
  project_id: string;
  type: 'post' | 'comment' | 'creator';
  target_id: string;
  lead_score?: number | null;
  reason?: string;
  is_valid: boolean;
  created_at: string;
}
export const createLead = async (leadData: any) => {
  const now = new Date().toISOString();
  const user = await getUser();
  if (!user) {
    return { data: null, error: 'User not found' };
  }
  const data: { data: LeadData | null, error: Error | null } = await supabase
    .from('leads')
    .insert({
      ...leadData,
      user_id: user.id,
      created_at: now,
    })
    .select()
    .single();
  return data;
}

export const deleteLead = async (result_id: string) => {
  const data: { data: LeadData[] | null, error: Error | null } = await supabase
    .from('leads')
    .delete()
    .eq('result_id', result_id)
    .select()
  return data;
}

export const getLeadsByUserId = async () => {
  const user = await getUser();
  if (!user) {
    return { data: null, error: 'User not found' };
  }
  const data: { data: LeadData[] | null, error: Error | null } = await supabase
    .from('leads')
    .select('*')
    .eq('user_id', user.id)
    .order('created_at', { ascending: false });
  return data;
}


// 定义公共详情数据接口
// 基础字段类型，用于索引签名
type BaseFieldValue = string | number | boolean | null | undefined;

// 创作者详情接口
export interface CreatorDetails {
  creator_id: string;
  name: string;
  platform: string;
  followers_count?: number;
  // 使用更具体的类型代替any
  [key: string]: BaseFieldValue;
}

// 帖子详情接口
export interface PostDetails {
  post_id: string;
  creator_id: string;
  content?: string;
  likes_count?: number;
  comments_count?: number;
  // 使用更具体的类型代替any
  [key: string]: BaseFieldValue;
}

export type PublicDetails = CreatorDetails | PostDetails | null;

/**
 * 获取公共详情数据
 * @param type 详情类型 (creator或post)
 * @param targetId 目标ID
 * @returns 详情数据或错误信息
 */
export const getPublicDetails = async (type: string, targetId: string): Promise<{ data: PublicDetails; error: string | null }> => {
  if (!type || !targetId) {
    return { data: null, error: 'missing params' };
  }
  if (type === 'creator') {
    const { data, error } = await supabase
      .from('creators')
      .select('*')
      .eq('creator_id', targetId)
      .single();
    return { data, error: error ? 'Failed to get creator details' : null };
  } else if (type === 'post') {
    const { data, error } = await supabase
      .from('posts')
      .select('*')
      .eq('post_id', targetId)
      .single();
    return { data, error: error ? 'Failed to get post details' : null };
  }
  return { data: null, error: 'invalid type' };
}


/**
 * 更新线索分数和原因
 * @param leadId 线索ID
 * @param leadScore 线索评分
 * @param reason 挖掘理由
 * @returns 更新后的线索数据或错误信息
 */
export const updateLeadDetails = async (
  leadId: string,
  leadScore?: number | null,
  reason?: string | null
): Promise<{ data: LeadData | null, error: string | null }> => {

  if (!leadId) {
    return { data: null, error: 'missing Params' };
  }

  // 检查线索是否存在且用户有权限
  const { data: lead, error: leadError } = await supabase
    .from('leads')
    .select('user_id, project_id')
    .eq('lead_id', leadId)
    .single();

  if (leadError || !lead) {
    return { data: null, error: 'not found' };
  }


  // 准备更新数据
  const updateData: { lead_score?: number | null; reason?: string | null } = {};

  if (leadScore !== undefined) {
    updateData.lead_score = leadScore;
  }

  if (reason !== undefined) {
    updateData.reason = reason;
  }

  // 更新线索详情
  const { data: updatedLead, error: updateError } = await supabase
    .from('leads')
    .update(updateData)
    .eq('lead_id', leadId)
    .select()
    .single();

  if (updateError) {
    console.error('更新线索详情失败:', updateError);
    return { data: null, error: 'update details failed' };
  }

  return { data: updatedLead, error: null };
};


/**
 * 更新线索有效性
 * @param leadId 线索ID
 * @param isValid 是否有效
 * @returns 更新后的线索数据或错误信息
 */
export const updateLeadValidity = async (leadId: string, isValid: boolean): Promise<{ data: LeadData | null, error: string | null }> => {

  if (!leadId) {
    return { data: null, error: 'missing Params' };
  }

  // 检查线索是否存在且用户有权限
  const { data: lead, error: leadError } = await supabase
    .from('leads')
    .select('user_id, project_id')
    .eq('lead_id', leadId)
    .single();

  if (leadError || !lead) {
    return { data: null, error: 'not Found' };
  }

  // 更新线索有效性
  const { data: updatedLead, error: updateError } = await supabase
    .from('leads')
    .update({
      is_valid: isValid
    })
    .eq('lead_id', leadId)
    .select()
    .single();

  if (updateError) {
    console.error('更新线索有效性失败:', updateError);
    return { data: null, error: 'update Failed' };
  }

  return { data: updatedLead, error: null };
};